<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\store\controller\dealer;

use think\response\Json;
use app\store\controller\Controller;
use app\store\model\dealer\User as UserModel;
use app\store\model\dealer\Referee as RefereeModel;
use app\common\service\qrcode\Poster;
use cores\exception\BaseException;

/**
 * 分销商管理
 * Class User
 * @package app\store\controller\apps\dealer
 */
class User extends Controller
{
    /**
     * 分销商用户列表
     * @param string $search 搜索内容
     * @return Json
     */
    public function list(string $search = ''): Json
    {
        $model = new UserModel;
        $list = $model->getList($search);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 分销商粉丝列表
     * @param int $dealerId 分销商ID
     * @return Json
     */
    public function fans(int $dealerId): Json
    {
        $model = new RefereeModel;
        $list = $model->getList($dealerId, $this->request->param());
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 编辑分销商
     * @param int $dealerId 分销商ID
     * @return Json
     */
    public function edit(int $dealerId): Json
    {
        $model = UserModel::detail($dealerId);
        if ($model->edit($this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除分销商
     * @param int $dealerId 分销商ID
     * @return Json
     */
    public function delete(int $dealerId): Json
    {
        $model = UserModel::detail($dealerId);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 分销商二维码
     * @param int $dealerId 分销商ID
     * @param string $channel 渠道
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function poster(int $dealerId, string $channel = 'H5'): Json
    {
        $model = UserModel::detail($dealerId);
        $Qrcode = new Poster($model, $channel);
        return $this->renderSuccess(['imageUrl' => $Qrcode->getImage()]);
    }
}